package com.projectc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.projectc.db.dao.UsersDAO;
import com.projectc.db.entities.User;

@SuppressWarnings("serial")
public class UsersServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse response) throws IOException {

		UsersDAO usersDao = new UsersDAO();
		// 1. get userlist
		List<User> users = usersDao.getAllUsers();

		// 2. initiate jackson mapper
		ObjectMapper mapper = new ObjectMapper();

		// 4. Set response type to JSON
		response.setContentType("application/json");

		// 6. Send List<Article> as JSON to client
		mapper.writeValue(response.getOutputStream(), users);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 1. get received JSON data from request
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
		String json = "";
		if (br != null) {
			json = br.readLine();
		}

		// 2. initiate jackson mapper
		ObjectMapper mapper = new ObjectMapper();

		// 3. Convert received JSON to user
		User user = mapper.readValue(json, User.class);

		UsersDAO usersDao = new UsersDAO();
		usersDao.create(user);
	}
}